<template>
  <!-- 添加或修改商品对话框 -->
  <div class="back-item product-details" v-if="open">
    <div class="right-detail">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="closEdits">取 消</el-button>
    </div>
    <el-form class="product-form" ref="productForm" :model="form" :inline="true" :rules="rules" label-width="80px">
      <h3>1基础信息</h3>
      <el-form-item label="商品名" prop="productName">
        <el-input v-model="form.productName" placeholder="请输入商品名"/>
      </el-form-item>
      <el-form-item class="all-width" label="商品图" prop="mallProductImgs">
        <div class="all-width">
          <img-upload v-model="item.productImg" v-for="(item,index) in form.mallProductImgs"/>
        </div>
      </el-form-item>
      <!--<el-form-item label="视频链接" prop="productVideo">
        <el-input v-model="form.productVideo" placeholder="请输入视频链接"/>
      </el-form-item>-->
      <el-form-item label="品牌" prop="brandId">
        <el-select v-model="form.brandId"  placeholder="请选择品牌">
          <el-option :label="item.brandName" :value="item.brandId" v-for="(item,index) in brandList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="labelId">

        <el-select v-model="form.labelId"  placeholder="请选择品牌">
          <el-option :label="item.labelName" :value="item.labelId" v-for="(item,index) in labelList" :key="index"/>
        </el-select>
      </el-form-item>

      <el-form-item label="商品品类" prop="firstCategoryId">
        <el-cascader
          v-model="categoryIds.formIds"
          :options="categoryTree"
          :props="{label:'categoryName',value:'categoryId'}"
          @change="handleFormSort"
          placeholder="请选择品类信息"
          filterable
        />
      </el-form-item>
      <el-form-item label="虚拟销量" prop="virtualNum">
        <el-input v-model="form.virtualNum" placeholder="请输入虚拟销量"/>
      </el-form-item>
      <h3>2.规格信息</h3>
      <el-form-item label="商品规格" class="form-standards" prop="mallProductStandards">
        <el-row class="standard-name" :gutter="20" v-for="(item1,index1) in standardObj.standardArr" :key="index1">
          <el-col :span="24">
            <el-button>
              {{item1.standardName}}
              <el-icon class="el-icon--right" @click="delStandard(index1)">
                <Close/>
              </el-icon>
            </el-button>
          </el-col>
          <el-tag
            v-for="(item2,index2) in item1.standardValue"
            :key="index2"
            class="mx-5"
            closable
            :disable-transitions="false"
            @close="delStandardValue(item1.standardValue,index2)"
          >
            {{item2.value}}
          </el-tag>
          <el-input
            v-if="item1.addValue"
            v-model="item1.valueItem"
            ref="InputRef"
            class="tag-input"
            size="small"
            autofocus
            @keyup.enter="addStandardValueCommit(index1)"
            @blur="addStandardValueCommit(index1)"
          >
          </el-input>
          <el-button v-else class="tag-input" size="small" @click="addStandardValue(index1)">
            + 新 增
          </el-button>
        </el-row>
        <el-row class="standard-name" :gutter="20" v-if="standardObj.addState">
          <el-col :span="2" class="input-label">品类名</el-col>
          <el-col :span="4">
            <el-input
              size="small"
              v-model="standardObj.standardAdd.name"
            />
          </el-col>
          <el-col :span="2" class="input-label">品类值</el-col>
          <el-col :span="4">
            <el-input
              size="small"
              v-model="standardObj.standardAdd.value"
            />
          </el-col>
          <el-col :span="2">
            <el-button
              size="mini"
              type="text"
              @click="standardAddCommit"
            >确定
            </el-button>
          </el-col>
          <el-col :span="2">
            <el-button
              size="mini"
              type="text"
              class="text-danger"
              @click="standardAddCancel"
            >取消
            </el-button>
          </el-col>
        </el-row>
        <el-row class="standard-name" :gutter="20" v-if="standardObj.standardArr.length < 3 && !standardObj.addState">
          <el-col :span="4">
            <el-button
              type="primary"
              size="mini"
              @click="addStandar"
            >新增
            </el-button>
          </el-col>

        </el-row>
      </el-form-item>
      <el-form-item label="规格属性" prop="mallGoods" class="form-standards" v-if="standardObj.standardArr.length">
        <el-table :data="goodsList">
          <el-table-column :label="item.title" :prop="value" align="center" v-for="(item,value) in standardTitle" :key="value"/>
          <el-table-column :label="item.title" width="130" align="center" v-for="(item,value) in goodsTitle" :key="value" >
            <template #default="scope" v-if="item.title=='ID'||item.title=='图片'">
              <span v-if="item.title=='ID'"> {{scope.row[value]}}</span>
              <img-upload v-else v-model="scope.row[value]" class="sku_upload"></img-upload>
            </template>
            <template #default="scope" v-else>
              <el-input v-model="scope.row[value]"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                icon="Delete"
                class="text-danger"
                @click="delGoods(scope.$index)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <h3>3.其他信息>></h3>
      <!--<el-form-item label="供应商" prop="supplierId">
        <el-input v-model="form.supplierId" placeholder="请输入供应商"/>
      </el-form-item>-->
      <!--<el-form-item label="真实销量" prop="saleNum">
        <el-input v-model="form.saleNum" placeholder="请输入真实销量"/>
      </el-form-item>-->
      <el-form-item label="邮费模板" prop="templateId">
        <el-input v-model="form.templateId" placeholder="请输入邮费模板"/>
      </el-form-item>

      <!--<el-form-item label="库存" prop="totalNum">
        <el-input v-model="form.totalNum" placeholder="请输入库存"/>
      </el-form-item>-->
      <!--<el-form-item label="商品价格" prop="salePrice">
        <el-input v-model="form.salePrice" placeholder="请输入商品价格"/>
      </el-form-item>-->
      <!--<el-form-item label="划线价" prop="linePrice">
        <el-input v-model="form.linePrice" placeholder="请输入划线价"/>
      </el-form-item>-->
      <el-form-item label="发货地" prop="origin">
        <el-cascader
          v-model="originArr"
          :options="regionData"
          @change="regionChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="邮费类型" prop="postage">
        <el-select v-model="form.postage"  placeholder="请选择邮费类型">
          <el-option label="包邮" value="0" />
          <el-option label="自费" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="详情" prop="details">
        <!--<el-input v-model="form.details" type="textarea" placeholder="请输入内容"/>-->
        <editor
          v-model="form.details"
        ></editor>
      </el-form-item>
    </el-form>

    <div class="right-detail">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="closEdits">取 消</el-button>
    </div>
    <div class="line-magin"></div>
  </div>

</template>

<script setup name="edits">
  import {listProduct, getProduct, delProduct, addProduct, updateProduct} from "@/api/mall/product";
  import { listBrand, } from "@/api/mall/brand";
  import { listLabel, } from "@/api/mall/label";
  import { listStandard, } from "@/api/mall/standard";
  import {treeListCategory,} from "@/api/mall/category";
  import Editor from '@/components/Editor/index';
  import * as areaData from "@/utils/areaData.js"

  const props = defineProps({
    id: {
      default: 14,
    },
    title: {
      type: String,
      default: ""
    }
  })
  const {proxy} = getCurrentInstance();
  const emit = defineEmits();
  import imgUpload from "@/components/upload/imgUpload";

  //商品品类树
  const categoryTree = ref([]);
  //商品规格编辑

  // 弹出层标题
  const title = ref("");
  // 弹出层
  const open = ref(false);
  // 表单参数
  const form = ref({});
  //商品属性
  const goodsList = ref([]);
  //商品品牌
  const brandList = ref([]);
  //商品标签
  const labelList = ref([]);

  //发货单选择
  const originArr = ref([])

  //商品属性名称
  const goodsTitle = ref({
    goodsId: {
      title: "ID",
    },
    goodsImg: {
      title: "图片",
    },
    salePrice: {
      title: "销售价",
    },
    costPrice: {
      title: "成本价",
    },
    linePrice: {
      title: "划线价",
    },
    totalNum: {
      title: "库存量",
    },
    weight: {
      title: "重量(KG）",
    },
    volume: {
      title: "体积(m³)",
    },

  })
  //规格属性名称
  const standardTitle = ref({})

  const data = reactive({
    rules: {
      firstCategoryId: [
        {required: true, message: "一级品类不能为空", trigger: "blur"}
      ],
      secondCategoryId: [
        {required: true, message: "二级品类不能为空", trigger: "blur"}
      ],
      thirdCategoryId: [
        {required: true, message: "三级品类不能为空", trigger: "blur"}
      ],
      postage: [
        {required: true, message: "邮费类型不能为空", trigger: "blur"}
      ],
      auditStatus: [
        {required: true, message: "审核状态不能为空", trigger: "blur"}
      ],
    },
    categoryIds: {
      queryIds: [],
      formIds: [],
    },
    standardObj: {standardArr: [],addState: false,standardAdd: {name: "", value: ""}},

  })

  const {rules, categoryIds, standardObj, } = toRefs(data);
  const { regionData, TextToCode, CodeToText } = toRefs(areaData);

  /** 获取详细信息 */
  function getDate() {
    if(props.id){
      getProduct(props.id).then(response => {
        form.value = response.data;
        let n = 4-form.value.mallProductImgs.length;
        for (let i = 0; i < n; i++){
          form.value.mallProductImgs.push({ productImg: null, })
        }
        goodsList.value = form.value.mallGoods;
        standardObj.value.standardArr = []
        for (let item of form.value.mallProductStandards){
          let standardItemObj = {
            standardName: item.standardName,
            standardValue: JSON.parse(item.standardValue)
          }
          standardObj.value.standardArr.push(standardItemObj)
        }
        categoryIds.value.formIds = [form.value.firstCategoryId,form.value.secondCategoryId,form.value.thirdCategoryId]
        if(form.value.origin){
          let originItemArr = form.value.origin.split("|");
          originArr.value = [
            TextToCode.value[originItemArr[0]].code,
            TextToCode.value[originItemArr[0]][originItemArr[1]].code,
            TextToCode.value[originItemArr[0]][originItemArr[1]][originItemArr[2]].code
          ]
        }
        open.value = true;
        title.value = "修改商品";
      }).catch(err => {
        closEdits()
      });
    }else {
      reset();
      open.value = true;
    }

  }

  //获取树形品类列表
  function getCategoryTree(){
    treeListCategory().then(response => {
      categoryTree.value = response.data
    })
  }

  //获取商品品牌列表
  function getBrandList(){
    listBrand().then(response => {
      brandList.value = response.rows
    })
  }

  //获取商品标签列表
  function getLabelList(){
    listLabel().then(response => {
      labelList.value = response.rows
    })
  }
  //获取预设规格信息
  function getStandardList(){
    if( form.value.mallGoods && form.value.mallGoods.length){
      return;
    }
    let standarQuery = {
      firstCategoryId: form.value.firstCategoryId,
      secondCategoryId: form.value.secondCategoryId,
      thirdCategoryId: form.value.thirdCategoryId,
    }
    listStandard(standarQuery).then(response => {
      //standardObj.value.standardArr = response.
      standardObj.value.standardArr = response.rows.map((item,index) => {
        return  { standardName: item.standardName, standardValue: JSON.parse(item.standard)}
      })
    })
  }

  /** 品类选择-form */
  function handleFormSort(values){
    if (values&&values.length == 3){
      form.value.firstCategoryId = values[0];
      form.value.secondCategoryId = values[1];
      form.value.thirdCategoryId = values[2];
      getStandardList(form.value)
    }else {
      if(values){
        categoryIds.value.formIds = [];
        proxy.$modal.msgWarning("请选择完整品类!")
      }
      form.value.firstCategoryId = null;
      form.value.secondCategoryId = null;
      form.value.thirdCategoryId = null;
    }
  }
  /** 关闭弹窗 */
  function closEdits(refresh) {
    reset();
    open.value = false;
    emit("closedits", refresh);

  }

  /** 表单重置 */
  function reset() {
    form.value = {
      productId: null,
      productName: null,
      firstImg: null,
      brandId: null,
      labelId: null,
      templateId: null,
      firstCategoryId: null,
      secondCategoryId: null,
      thirdCategoryId: null,
      supplierId: null,
      saleNum: null,
      virtualNum: null,
      productVideo: null,
      totalNum: null,
      salePrice: null,
      linePrice: null,
      mallGoods: [],
      mallProductImgs: [
        {
          productImg: null,
        },
        {
          productImg: null,
        },
        {
          productImg: null,
        },
        {
          productImg: null,
        },

      ],
      mallProductStandards: [],
      origin: null,
      postage: null,
      status: "0",
      auditStatus: "0",
      invoiceStatus: "0",
      createTime: null,
      createBy: null,
      updateTime: null,
      details: null,
    };
    proxy.resetForm("userForm");
  }

  /** 提交按钮操作 */
  function submitForm() {
    form.value.mallProductStandards = []
    for (let item of standardObj.value.standardArr){
      let standardItemObj = {
        standardName: item.standardName,
        standardValue: JSON.stringify(item.standardValue)
      }
      form.value.mallProductStandards.push(standardItemObj)
    }
    form.value.mallGoods = goodsList.value
    proxy.$refs["productForm"].validate(valid => {
      if (valid) {
        if (form.value.productId) {
          updateProduct(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            closEdits(true);
          });
        } else {
          addProduct(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            closEdits(true);
          });
        }
      }else {
        proxy.$modal.msgWarning("参数不完整！")
      }
    })
  }

  /** 新增规格 */
  function addStandar() {
    standardObj.value.addState = true;
  }
  /** 新增规格确定 */
  function standardAddCommit() {
    if (!standardObj.value.standardAdd.name) {
      proxy.$modal.msgError("请输入规格名");
      return ;
    }
    if (!standardObj.value.standardAdd.value) {
      proxy.$modal.msgError("请输入规格值");
      return ;
    }
    let standarItem = {
      standardName: standardObj.value.standardAdd.name,
      standardValue: [{value: standardObj.value.standardAdd.value}],
      addValue: false,
      valueItem: "",
    }
    standardObj.value.standardArr.push(standarItem);
    standardObj.value.addState = false;
    standardObj.value.standardAdd.name = ""
    standardObj.value.standardAdd.value = ""
  }
  /** 新增规格取消 */
  function standardAddCancel() {
    standardObj.value.addState = false;
    standardObj.value.standardAdd.name = ""
    standardObj.value.standardAdd.value = ""
  }
  function delStandard(index) {
    standardObj.value.standardArr.splice(index,1)
  }
  /** 新增规格值按钮 */
  function addStandardValue(index) {
    standardObj.value.standardArr[index].valueItem = "";
    standardObj.value.standardArr[index].addValue = true;
  }
  /** 新增规格值确认 */
  function addStandardValueCommit(index) {
    if(!standardObj.value.standardArr[index].valueItem){
      proxy.$modal.msgError("请输入规格值");
      standardObj.value.standardArr[index].addValue = false;
      return ;
    }
    let standardValueItem = {value: standardObj.value.standardArr[index].valueItem};
    standardObj.value.standardArr[index].standardValue.push(standardValueItem);
    standardObj.value.standardArr[index].addValue = false;
    standardObj.value.standardArr[index].valueItem = "";
  }
  function delStandardValue(standardValue,index) {
    standardValue.splice(index,1)
  }
  function setGoodsArr(){

    let list = []
    standardObj.value.standardArr.forEach((item,index) => {
      let keys = "key" + (index + 1)
      standardTitle.value[keys] = {title: item.standardName}
      list =  ergodicStandard(item,list,keys)
    })

    for (let item of list){
      for (let title in goodsTitle.value){
        item[title] = ""
      }
    }

    //判断是否生成新的商品规格表
    let skuRefresh = true;
    if (form.value.mallProductStandards.length){
      let oldStandards = []
      for (let item of form.value.mallProductStandards){
        let standardItem = {
          standardName: item.standardName,
          standardValue: JSON.parse(item.standardValue),
        }
        oldStandards.push(standardItem);
      }
      let oldStandardsJson = JSON.stringify(oldStandards)
      let newStandardsJson = JSON.stringify(standardObj.value.standardArr)
      skuRefresh = !(oldStandardsJson == newStandardsJson);
    }
    if(skuRefresh){
      if (goodsList.value.length){
        list.forEach((item1,index) => {
          for (let item2 of goodsList.value){
            if(item1.standardJson == item2.standardJson){
              list.splice(index,1,item2)
            }
          }
        })
      }
    }else {
      list = []
      form.value.mallGoods.forEach((item1,index1) => {
        let standardJsonObj = JSON.parse(item1.standardJson);
        standardJsonObj.forEach((item2,index2) => {
          item1["key"+ (index2 + 1)] = item2.value
        })
        let goodsItem = Object.assign({},item1)
        list.push(goodsItem);
      })
    }
    goodsList.value = list
  }

  function ergodicStandard(standardItem,list,keys) {
    let list2 = []
    if (list.length == 0){
      for (let item1 of standardItem.standardValue){
        let goodsObj = {};
        let standardJson = [{key:standardItem.standardName,value:item1.value}];
        goodsObj[keys] = item1.value;
        goodsObj["standardJson"] = JSON.stringify(standardJson);
        list2.push(goodsObj);
      }
    }else {
      for (let item1 of list){
        let item1StandardJson = JSON.parse(item1.standardJson)
        for (let item2 of standardItem.standardValue){
          let goodsObj = {};
          goodsObj[keys] = item2.value;
          let standardJson = [{key:standardItem.standardName,value:item2.value}];
          goodsObj = Object.assign(goodsObj,item1)
          goodsObj.standardJson = JSON.stringify(item1StandardJson.concat(standardJson))
          list2.push(goodsObj)
        }
      }

    }
    return list2;

  }
  //删除商品属性
  function delGoods(index){
    goodsList.value.splice(index,1);
  }
  //地址选择
  function regionChange(option) {

    if (option&&option.length==3){
      form.value.origin = `${CodeToText.value[option[0]]}|${CodeToText.value[option[1]]}|${CodeToText.value[option[2]]}`;
    }else {
      form.value.origin = null;
      if (option&&option.length<3){
        proxy.$modal.msgWarning("请选择正确的地址！");
        return;
      }

    }



  }

  watch(() => standardObj.value.standardArr, val => {
      setGoodsArr();
    },
    //深度监听
    {deep: true}
  );
  getDate();
  getBrandList();
  getLabelList();
  getCategoryTree();
</script>

<style lang="scss">
  .product-details{
    max-width: 900px;
    margin: auto;
    .right-detail{
      text-align: right;
    }
    .product-form{
      margin-top: 20px;
      display: flex;
      flex-wrap: wrap;
      h3{
        width: 100%;
      }
      .el-form-item{
        min-width: 350px;
        margin-left: 25px;
        margin-right: 25px;
      }
      .form-standards{
        width: 100%;
        .standard-name{
          margin-bottom: 14px;
        }
        .el-tag{
          margin:8px 8px 0;
        }
        .tag-input{
          width: 87.2px;
          height: 28px;
          line-height: 28px;
          padding: 0;
          margin:8px 8px 0;

        }
        .el-input--small .el-input__inner {
          height: 28px  !important;
        }
        .el-button--small{
          height: 28px !important;
          min-height: 28px !important;
        }
        .input-label{
          text-align: right;
          //background-color: #0A98D5;
        }
      }

    }
  }
  .all-width{
    width: 100%;
    display: flex;
  }
</style>